package com.niannian.db;

import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import com.niannian.util.DBPreferBeanHelper;

public class DBSettings extends DBPreferBeanHelper {
	public static final String ID = "id";
	public int id = 0;

	public static final String UID = "uid";
	public int uid = 0;

	public static final String ITEM = "item";
	public int item = 0;

	public static final String SETTING = "setting";
	public String setting = "";

	public void init(Context cont) {
		super.init(cont);
		String table_name = "is_settings";
		String create_table = "CREATE TABLE IF NOT EXISTS " + table_name + "("
				+ "[id] INTEGER NOT NULL PRIMARY KEY DEFAULT 0,"
				+ "[uid] INTEGER NOT NULL  DEFAULT 0,"
				+ "[item] INTEGER NOT NULL DEFAULT 0,"
				+ "[setting] TEXT NOT NULL DEFAULT (''));";
		super.setDatatableName(table_name, create_table);
		addPrimaryKey(ID);
	}

	public DBSettings getUserSettings(int uid, int item) {
		Map<String, Object> where = new HashMap<String, Object>();
		where.put("uid", uid);
		where.put("item", item);
		loadFromDB(where);
		return this;
	}

	public void Json2DBSetting(JSONObject json) throws JSONException {
		this.id = json.getInt(ID);
		this.uid = json.getInt(UID);
		this.item = json.getInt(ITEM);
		this.setting = json.getString(SETTING);
	}

	public boolean updateDBSetting() {
		try {
			updateAll();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public boolean isDataInvalid() {
		if (this.uid == 0) {
			return true;
		} else
			return false;
	}

	@Override
	public void setDataInvalid() {
		this.uid = 0;
		try {
			clearPref();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
